package com.xtr.controller;

import com.lcn.comm.util.DateUtil;
import com.weibo.api.motan.util.LoggerUtil;
import com.xtr.tx.service.SysTestService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @createTime: 2017/11/17 14:32
 */
@Controller
public class TestController {

    private static final Logger LOGGER = LogManager.getLogger(TestController.class);

    private ExecutorService pool;

    @Resource
    private SysTestService sysTestService;

    @GetMapping("test")
    @ResponseBody
    public String test() {
        try {
            LoggerUtil.info("测试·······················");
            Long startTime = System.currentTimeMillis();
            List<Future> rowResult = new CopyOnWriteArrayList<Future>();
            pool = Executors.newFixedThreadPool(30);
            for (int i = 0; i < 1000; i++) {
                final int finalI = i;
                rowResult.add(pool.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sysTestService.test();
//                        sysTestService.test1();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }));
            }
            //等待处理结果
            for (Future f : rowResult) {
                f.get();
            }
            //启动一次顺序关闭，执行以前提交的任务，但不接受新任务。如果已经关闭，则调用没有其他作用
            pool.shutdown();
            System.out.println("测试耗时：" + DateUtil.dateDiff(startTime, System.currentTimeMillis()));
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage(), e);
        }
        return "1";
    }

    @GetMapping("test1")
    @ResponseBody
    public void test1() {
        Long startTime = System.currentTimeMillis();
        try {
            sysTestService.test1();
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }finally {
            LOGGER.info("测试1耗时：" + DateUtil.dateDiff(startTime, System.currentTimeMillis()));
        }
        test2();
    }

    private void test2(){
        Long startTime = System.currentTimeMillis();
        try {
            sysTestService.test1();
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }finally {
            LOGGER.info("测试2耗时：" + DateUtil.dateDiff(startTime, System.currentTimeMillis()));
        }
    }
}
